package network;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;

public class ServerSimulator implements Runnable {
	ServerSocket ss;
	static Random rand = new Random();
	
	public ServerSimulator() {
		try {
			ss = new ServerSocket(8000);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private String randomString(int maxlen) {
		int len;
		len = rand.nextInt(maxlen-1)+1;
		byte[] byteval = new byte[len];
		rand.nextBytes(byteval);
		for (int i=0; i<len; ++i)
			byteval[i] = (byte) ('A' + rand.nextInt('z'-'A'));
		return new String(byteval);
	}
	
	@Override
	public void run() {
		try {
			System.out.println("start listening...");
			Socket client = ss.accept();
			ss.close();
			System.out.println(client.getInetAddress().getHostAddress()
					+ ":" + client.getPort()
					+ " connected.");
			PrintWriter pw = new PrintWriter(client.getOutputStream());
			for (int i=0; i<1000; ++i) {
				String theS = randomString(10000);
				theS = i + " " + theS; 
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
//				System.out.println("send string length = " + (theS.length()+2));
//				System.out.println(theS);
				pw.println(theS);
				if (pw.checkError()) {
					System.out.println("connection abort.\n");
					System.out.println("start listening...");
					ss = new ServerSocket(ss.getLocalPort());
					client.close();
					client = ss.accept();
					ss.close();
					System.out.println(client.getInetAddress().getHostAddress()
							+ ":" + client.getPort()
							+ " connected.");
					pw.close();
					pw = new PrintWriter(client.getOutputStream());
				}
//				pw.flush();
			}
			pw.close();
			client.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		new ServerSimulator().run();
	}
}
